class Post < ApplicationRecord
  include Slugable
  validates_presence_of :body, :user_id
  belongs_to :user
  default_scope {where(parent_id: nil)}

  def versions
    Post.unscoped.where(main_id: self.id)
  end

  def custom_clone
    new_post = self.dup
    new_post.slug = nil
    new_post.created_at = nil
    new_post.updated_at = nil
    new_post.parent_id = self.find_parend_post_id
    new_post.main_id = self.find_main_post_id
    new_post.version = Time.now
    return new_post
  end

  def find_parend_post_id
    return self.id if self.versions.count == 0
    self.versions.last.id
  end

  def find_main_post_id
    return self.id if self.parent_id.nil?
    parent = Post.find(self.parent_id)
    parent.find_main_post_id
  end
end
